Ext.define('AmpleHarvest.views.search.searchBox',
{
    extend          : 'Ext.panel.Panel',
    alias           : 'widget.ampleharvest-views-search-searchbox',
    anchor          : '100% 100%',
    layout          : 'border',
    listeners       :
    {
        updateAll : function()
        {
            // TODO:  update all children based on passed values
        }
    },
    
    initComponent   : function()
    {
    	this.str_unique_id = (((1+Math.random())*0x10000)|0).toString(16).substring(1);

        this.m_obj_search = Ext.create( this.obj_config.form,
//        this.m_obj_search = Ext.create( this.obj_form_info.str_form_path,
                {
                    region  		: "center",
                    flex    		: 2,
                    autoScroll		: true,
                    str_solr_base	: this.obj_config.solr,
//                    str_solr_base	: this.obj_form_info.str_solr_base,
                    tbar			: [
						Ext.create('Ext.button.Button',
								{
									text	: 'Add Facet',
									dock	: 'top',
									scope	: this,
									handler	: function()
									{
										m_obj_AmpleHarvest_ViewPort.mask();						
										m_obj_AmpleHarvest_ViewPort
											.fireEvent(AmpleHarvest.eventHandler.cWindowEvents.C_STR_EVENT_SEARCH_FACET_FORM
													,Ext.getCmp('ampleHarvest-objects-forms-textarea'+this.str_unique_id)
													,'');
									}
								}	
						)
                        			   ],
                    buttons			: [
           			    {
					         text     : 'Save',
					         flex		: 1,
//					         disabled : true,
					         scope    : this,
					         handler     : function()
					         {
					        	 var obj_query = this.get_QueryObject(this.m_obj_search.getForm());
					        	 
				        	 	 m_obj_AmpleHarvest_ViewPort.fireEvent(
					                        AmpleHarvest.eventHandler.cWindowEvents.C_STR_EVENT_SAVED_QUERY_ADD,
					                        Ext.encode(obj_query),
					                        this.obj_config,
					                        this.m_obj_search.source_name
					                  );
					         }
           			   	},   			      			   
						{
						    text  	: "Reset",
						    flex		: 1,
						    dock	: 'bottom',
						    itemId	: 'ampleharvest-views-search-searchbox-buttons',
						    scope	: this,
						    handler  : function()
						    {
						       this.m_obj_search.getForm().reset();
						    }
						 },
						{
							text	: 'Submit',
							flex		: 1,
							alias   : 'widget.ampleharvest-views-search-submit',
							itemId	: 'ampleharvest-views-search-searchbox-submit',
							dock	: 'bottom',
							scope	: this,
							handler	: function() {
								this.submit_form();	
							}
						}
                           			   ],
                    str_unique_id	: this.str_unique_id
                }
        );
        
        var cQManagerRegion 	= 'south';
        if(this.region == 'north')
        {
        	cQManagerRegion 	= 'east';
        }
        
	    this.m_obj_preview = Ext.create(
	            "AmpleHarvest.objects.querymanager.cQueryManager",
	            {
	            	m_str_view_type   	: 'mini',
	            	str_form_path		: this.obj_config.form,
	                region  			: cQManagerRegion,
	                str_sourceName		: this.m_obj_search.source_name,
	                flex   				: 1
	            }
	    );
	    
        this.items =
        [
                this.m_obj_search,
                this.m_obj_preview
        ];
        
        this.callParent();
        
        this.on('afterrender', function() {
        	
        		console.log(this.m_obj_search)
        	
	            this.keyNav = Ext.create('Ext.util.KeyNav', this.el, {
	                enter: this.submit_form,
	                scope: this
	              });
        	
        	
        		if(Ext.isObject(this.obj_config.run))
//	        	if(Ext.isObject(this.obj_form_info.obj_run_search))
	        	{
        			this.preload_form(this.obj_config.run);
//	        		this.preload_form(this.obj_form_info.obj_run_search);
	        	}
        	});
    },
    

    submit_form			: function()
    {
    	m_obj_AmpleHarvest_ViewPort.fireEvent(AmpleHarvest.eventHandler.cWindowEvents.C_STR_EVENT_SEARCH,
				this.ownerCt.selfPath,
				this.ownerCt.itemId,
				this
		);
    },
    
    preload_form		: function(obj_search)
    {
    	var obj_Form = this.m_obj_search.getForm();
    	for (str_I in obj_search)
        {
    		var obj_field = obj_Form.findField(str_I);
    		if(obj_field.ownerCt instanceof Ext.form.FieldSet)
    		{
    			obj_field.ownerCt.expand();
    		}
    		if(obj_search[str_I]['type'] == 'date')
    		{
    			obj_search[str_I]['str_query'] = obj_search[str_I]['rawData'];
    		}
    		obj_Form.findField(str_I).setValue(obj_search[str_I]['str_query']);
        }
    	m_obj_AmpleHarvest_ViewPort.fireEvent(AmpleHarvest.eventHandler.cWindowEvents.C_STR_EVENT_SEARCH,
    			this.ownerCt.selfPath,
				this.ownerCt.itemId,
				this
		);
    },
    
    get_QueryObject		: function()
    {
    	var obj_Tmp = new Object();
    	var obj_Form = this.m_obj_search.getForm().getFields();
    	var str_and	= ' AND ';
//    	var str_or	= ' OR '; // not currently supported
//    	var str_not = ' NOT '; // not currently supported
    	
    	for (int_I in obj_Form.items)
        {
    		var obj_Item = obj_Form.items[int_I];
    		
    		if (!obj_Item.getValue())
    		{
				continue;
    		}
	       	       
    		if (obj_Item)
    		{
    			obj_Tmp[obj_Item.name] = new Object();
    			if(obj_Item.name == 'general')
    			{
    				obj_Tmp[obj_Item.name]['str_query'] = obj_Item.getValue();
    				obj_Tmp[obj_Item.name]['type'] = obj_Item.name;
	    		   	continue;
    			}
    			else if(obj_Item.dataType == 'date')
    			{
    				obj_Item.solr_format = Ext.Date.format(obj_Item.getValue(), 'Y-m-d H:i:s')+'Z';
    				obj_Item.solr_format = obj_Item.solr_format.replace(/ /g, 'T');
    				obj_Tmp[obj_Item.name]['rawData'] = Ext.Date.format(obj_Item.getValue(), 'Y-m-d H:i:s');
    			}
    			else
    			{
    				obj_Item.solr_format = obj_Item.getValue();
    			}
    			
    			obj_Tmp[obj_Item.name]['str_query'] = obj_Item.solr_format;
    			obj_Tmp[obj_Item.name]['term'] = obj_Item.searchTerm;
    			obj_Tmp[obj_Item.name]['type'] = obj_Item.dataType;  	    
    		}
		}
//    	this.ownerCt.lastQuery = obj_Tmp;
//    	this.ownerCt.obj_form_info.obj_run_search = obj_Tmp;
		return(obj_Tmp);
    },
    
    build_query	: function(obj_query)
    {
    	var str_solr_query = '';
    	var obj_rangeItems = new Object();
    	var str_startKey = '_start';
    	var str_endKey = '_end';
//    	console.log(obj_query);
    	for (str_key in obj_query)
        {
    		var str_each = '';
    		var str_quote_wrap = '';
    		var bool_end = true;
    		if(str_key == 'general')
    		{
    			str_each = obj_query[str_key]['str_query'];
    			bool_end = false;
    		}
    		else if(str_key.indexOf(str_startKey) > 0)
    		{
    			console.log('start');
    			if(!Ext.isObject(obj_rangeItems[obj_query[str_key]['term']]))
				{
    				obj_rangeItems[obj_query[str_key]['term']] = new Object();
				}
    			obj_rangeItems[obj_query[str_key]['term']][str_startKey] = obj_query[str_key]['str_query'];
    			obj_rangeItems[obj_query[str_key]['term']]['type'] = obj_query[str_key]['type'];
    			
    		}
    		else if(str_key.indexOf(str_endKey) > 0)
    		{
    			if(!Ext.isObject(obj_rangeItems[obj_query[str_key]['term']]))
				{	
    				obj_rangeItems[obj_query[str_key]['term']] = new Object();
				}
				obj_rangeItems[obj_query[str_key]['term']][str_endKey] = obj_query[str_key]['str_query'];
				obj_rangeItems[obj_query[str_key]['term']]['type'] = obj_query[str_key]['type'];
				
    		}
    		else
    		{
    			if(obj_query[str_key]['type'] == 'facet')
    			{
    				str_each = obj_query[str_key]['term']+':'+obj_query[str_key]['str_query'];
    			}
    		}
    		var str_temp = '';
    		if(str_each.length > 0)
    		{
    			if(bool_end)
    			{
    				if(str_solr_query.length > 0)
    				{
    					str_temp = str_solr_query+' AND ';
    				}
    				str_solr_query = str_temp+str_each;
    			}
    			else
    			{
    				if(str_solr_query.length > 0)
    				{
    					str_temp = ' AND '+str_solr_query;
    				}
    				str_solr_query = str_each+str_temp;
    			}
    		}
        }
    	var str_break = '';
    	for (str_key in obj_rangeItems)
        {
    		console.log(obj_rangeItems);
    		var str_range_solr_query = str_key+':';
    		var str_temp = '';
    		var bool_isDate = obj_rangeItems[str_key]['type'] == 'date' ? true : false;
    		var bool_start =  Ext.isDefined(obj_rangeItems[str_key][str_startKey]) ? true : false;
        	var bool_end = Ext.isDefined(obj_rangeItems[str_key][str_endKey]) ? true : false;
    		var str_range_start = bool_isDate  ? '"1976-03-06T23:59:59.999Z"' : '0';
    		var str_range_end = bool_isDate ? 'NOW' : '*';
    		var str_quote_wrap =  bool_isDate ? '"' : '';
    		
    		if(bool_start && bool_end)
    		{
    			str_range_solr_query += '['+str_quote_wrap+obj_rangeItems[str_key][str_startKey]+str_quote_wrap+' TO '+str_quote_wrap+obj_rangeItems[str_key][str_endKey]+str_quote_wrap+']';
    		}
    		else if (bool_start && !bool_end)
    		{
    			str_range_solr_query += '['+str_quote_wrap+obj_rangeItems[str_key][str_startKey]+str_quote_wrap+' TO '+str_range_end+']';
    		}
    		else if (!bool_start && bool_end)
    		{
    			str_range_solr_query += '['+str_range_start+' TO '+str_quote_wrap+obj_rangeItems[str_key][str_endKey]+str_quote_wrap+']';
    		}
    		if(str_solr_query.length > 0)
    		{
    			str_break = ' AND ';
    		}
    		str_solr_query += str_break+str_range_solr_query;
        }
//    	console.log(str_solr_query);
    	return str_solr_query;
    }
});


